<template>
  <div>
    <!--<el-form :inline="true">-->
    <!--<el-form-item>-->
    <!--<el-input placeholder="返厂批次号" v-model="batch"></el-input>-->
    <!--</el-form-item>-->
    <!--<el-form-item>-->
    <!--<el-input placeholder="快递单号" v-model="logisticNumber"></el-input>-->
    <!--</el-form-item>-->
    <!--<el-form-item>-->
    <!--<el-button type="primary" @click="searchDate()">查询</el-button>-->
    <!--</el-form-item>-->
    <!--</el-form>-->

    <custom-table
      :data="receiveList"
      :columns="columns"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <el-dialog title="收机备注说明" :visible.sync="remarkDialogVisible" :close-on-click-modal="false"
               :before-close="uploadCancel">
      <el-form :model="remarkDto" :rules="remarkRules" label-width="100px" ref="remarkForm">
        <el-form-item label="物流单号">
          <el-input v-model="remarkDto.logisticsNumber" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="型号">
          <el-input v-model="remarkDto.modelName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="remarkDto.num" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item>
          <a href="/static/调拨收机导入模板.xlsx" download="调拨收机导入模板.xlsx" style="color:#ffffff;text-decoration: none ">
            <el-button type="primary">模板下载</el-button>
          </a>
        </el-form-item>
        <el-form-item label="模板导入">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="myHeaders"
            name="file"
            :on-error="uploadError"
            :on-success="uploadSuccess"
            :before-upload="beforeAvatarUpload"
            multiple
            drag
            :limit="1"
            :file-list="fileList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
          </el-upload>
        </el-form-item>
        <div label="错误数据" style="height: 200px;overflow-y: auto;width:522px" v-if="hideTable">
          <custom-table
            :data="wrongDataList"
            :columns="detailColumns">
          </custom-table>
        </div>
      </el-form>
      <div slot="footer">
        <el-button @click="onBtnCancel('remarkForm')">取消</el-button>
        <el-button type="primary" @click="onBtnAccept">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {apiGetReceiveList, apiReceive} from '@/api/stock/index'
  import store from '@/store'
  import {getRoleType, getName, getOfficeType, getProvinceCode, getOfficeId, getOutsourceId} from '@/utils/token'
  import {baseInfo} from '@/utils/fetch'
  import {apiAllotReceiveReadExcel} from '@/api/excel/excelRead'
  import {parseTime} from '@/utils'

  export default {
    components: {
      CustomTable
    },
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        receiveProvince: getProvinceCode(),
        pointId: '',
        pointType: ''
      }
      this.def()
      this.getReceiveList(listQuery)
    },
    data () {
      return {
        pointId: '',
        pointType: '',
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        path: '',
        tableLoadingFlag: false,
        hideTable: false,
        wrongDataList: [],
        columns: [
          {label: '调拨单号', name: 'applicationNo', width: '150', align: 'center'},
          {label: '发放人', name: 'username', align: 'center'},
          {label: '发放省份', name: 'calloutProvinceName', align: 'center'},
          {label: '物流公司', name: 'logisticsCompany', align: 'center'},
          {label: '物流单号', name: 'logisticsNumber', align: 'center'},
          {label: '型号', name: 'modelName', align: 'center'},
          {label: '数量', name: 'num', align: 'center'}
        ],
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', width: '100', align: 'center'},
          {label: '错误原因', name: 'reason', width: '120', align: 'center'},
          {label: '型号', name: 'model', width: '100', align: 'center'},
          {label: 'SN号', name: 'ystsn', width: '100', align: 'center'}
        ],
        receiveList: [],
        roleType: getRoleType(),
        operationColumn: {
          width: '150',
          operations: [
            // {name: '备注说明', callback: this.onBtnRemark},
            {name: '确认收机', callback: this.onBtnRemark}
          ]
        },
        remarkDialogVisible: false,           // 备注说明模态框
        remarkDto: {
          logisticsNumber: '',
          logisticsId: '',
          modelName: '',
          num: '',
          id: '',
          operator: '',
          pointId: '',
          pointType: '',
          filePath: '',
          receiveDate: parseTime(new Date().getTime())
        },
        remarkRules: {
//          remark: [{required: true, message: '请输入原因', trigger: 'blur'}]
        },
        currentRow: null,
        pagination: this.getData(this.getReceiveList),
        batch: '',
        logisticNumber: ''
      }
    },
    methods: {
      uploadSuccess (response, file, fileList) {
        this.path = response.data
        this.$message({
          showClose: true,
          message: '上传文件成功！'
        })
        this.remarkDto.filePath = this.path
        let listQuery = {
          filePath: response.data,
          modelName: this.remarkDto.modelName
        }
        this.excelRead(listQuery)
      },
      // 上传错误
      uploadError (err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }
        return extension && isLt2M
      },
      excelRead (listQuery) {
        listQuery.logisticsId = this.remarkDto.logisticsId
        apiAllotReceiveReadExcel(listQuery).then(response => {
          if (response.data) {
            if (response.data[0].wrongRowNO) {
              this.wrongDataList = response.data
              this.hideTable = true
            } else {
              this.$message({
                showClose: true,
                message: '导入执行中，请稍后',
                type: 'success'
              })
              this.hideTable = false
            }
            this.fileList = []
          }
        })
      },
      getReceiveList (listQuery) {
        if (this.roleType === '2') {
          listQuery.pointType = 0
          listQuery.pointId = getOfficeId()
        } else if (this.roleType === '3') {
          listQuery.pointType = 1
          listQuery.pointId = getOutsourceId()
        }
        listQuery.receiveProvince = getProvinceCode()
        this.tableLoadingFlag = true
        apiGetReceiveList(listQuery).then(response => {
          this.receiveList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      onBtnAccept () {
        // 确认收机
        if (this.roleType === '2') {
          this.remarkDto.pointType = 0
          this.remarkDto.pointId = getOfficeId()
        } else if (this.roleType === '3') {
          this.remarkDto.pointType = 1
          this.remarkDto.pointId = getOutsourceId()
        }
        this.$refs['remarkForm'].validate((valid) => {
          if (valid) {
            this.$confirm('确认收机？', '确认', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.remarkDto.filePath = this.path
              apiReceive(this.remarkDto).then(rsp => {
                if (rsp.resCode === '200') {
                  this.$message({showClose: true, message: '确认收机', type: 'success'})
                  this.remarkDialogVisible = false
                } else {
                  this.$message({showClose: true, message: '收机失败', type: 'error'})
                }
                this.getReceiveList({})
              })
            }).catch(() => {
            })
          }
        })
      },
      onBtnRemark (row) {
        // 备注说明模态框
//        this.currentRow = row
        this.remarkDto.logisticsNumber = row.logisticsNumber
        this.remarkDto.modelName = row.modelName
        this.remarkDto.num = row.num
        this.remarkDto.id = row.allotId
        this.remarkDto.logisticsId = row.allotLogisticsId
        this.remarkDto.pointId = getOfficeId()   // this.pointId
        if (getRoleType() === '2') {
          this.remarkDto.pointType = 0
        }
        if (getRoleType() === '3') {
          this.remarkDto.pointType = 1
        }
        this.remarkDto.operator = getName()
        this.remarkDialogVisible = true
      },
      /* onBtnSubmit () {
        // 备注说明模态框确认按钮
        this.currentRow.remark = this.remarkDto.remark
        this.remarkDialogVisible = false
      }, */
      onBtnCancel (formName) {
        this.remarkDialogVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs[formName].resetFields()
      },
      uploadCancel() {
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.remarkDialogVisible = false
      },
      def () {
        if (this.roleType !== '2' && this.roleType !== '3') {
          this.operationColumn = null
        }
      }
    }
  }
</script>
